<template>
  <div>
    <el-button type="success" style="margin: 1vw" @click="getPermission()">
      获取麦克风权限
    </el-button>
    <br />

    <el-button type="info" style="margin: 1vw" @click="startRecorder()">
      开始录音
    </el-button>
    <button @click="timeStart()">点击</button>

    <button @click="stop">暂停</button>

    <button @click="reset">重置</button>

    <button @click="timeStart">继续</button>

    <h1>{{ str }}</h1>
    <br />
    <el-button type="info" style="margin: 1vw" @click="resumeRecorder()">
      继续录音
    </el-button>

    <el-button type="info" style="margin: 1vw" @click="pauseRecorder()">
      暂停录音
    </el-button>

    <el-button type="info" style="margin: 1vw" @click="stopRecorder()">
      结束录音
    </el-button>

    <br />

    <el-button type="success" style="margin: 1vw" @click="playRecorder()">
      录音播放
    </el-button>

    <el-button type="success" style="margin: 1vw" @click="pausePlayRecorder()">
      暂停录音播放
    </el-button>

    <el-button type="success" style="margin: 1vw" @click="resumePlayRecorder()">
      恢复录音播放
    </el-button>

    <el-button type="success" style="margin: 1vw" @click="stopPlayRecorder()">
      停止录音播放
    </el-button>

    <br />

    <el-button type="info" style="margin: 1vw" @click="getRecorder()">
      获取录音信息
    </el-button>

    <el-button type="info" style="margin: 1vw" @click="downPCM()">
      下载PCM
    </el-button>

    <el-button type="info" style="margin: 1vw" @click="downWAV()">
      下载WAV
    </el-button>

    <el-button type="info" style="margin: 1vw" @click="getMp3Data()">
      下载MP3
    </el-button>

    <br />

    <el-button type="error" style="margin: 1vw" @click="destroyRecorder()">
      销毁录音
    </el-button>
  </div>
</template>

<script>
  import Recorder from 'js-audio-recorder'

  const lamejs = require('lamejs')

  let recorder = new Recorder({
    sampleBits: 16, // 采样位数，支持 8 或 16，默认是16

    sampleRate: 48000, // 采样率，支持 11025、16000、22050、24000、44100、48000，根据浏览器默认值，我的chrome是48000

    numChannels: 1, // 声道，支持 1 或 2， 默认是1

    // compiling: false,(0.x版本中生效,1.x增加中) // 是否边录边转换，默认是false
  })
  export default {
    name: 'Records',
    data() {
      return {
        // timer: '',
        // hour: 0,
        // minutes: 0,
        // seconds: 0,
        // cr: '',
        time: '',
        hour: 0,
        minute: 0,
        second: 0,
        ms: 0,
        str: '',
      }
    },
    methods: {
      // // 计时计算规则
      // startTimer() {
      //   this.seconds += 1
      //   if (this.seconds >= 60) {
      //     this.seconds = 0
      //     this.minutes = this.minutes + 1
      //   }
      //
      //   if (this.minutes >= 60) {
      //     this.minutes = 0
      //     this.hour = this.hour + 1
      //   }
      //   this.$refs.startTimer.innerHTML =
      //     (this.hour < 10 ? '0' + this.hour : this.hour) +
      //     ':' +
      //     (this.minutes < 10 ? '0' + this.minutes : this.minutes) +
      //     ':' +
      //     (this.seconds < 10 ? '0' + this.seconds : this.seconds)
      //   this.cr = this.seconds
      // },
      // // 停止计时
      // stop() {
      //   clearInterval(this.timer)
      // },
      // // 计时开始
      // start() {
      //   this.timer = setInterval(this.startTimer, 1000)
      // },
      // 开始录音
      //计时器补0
      toDub(n) {
        //补0操作
        if (n < 10) {
          return '0' + n
        } else {
          return '' + n
        }
      },
      //暂停计时
      stop() {
        clearInterval(this.time)
      },
      //重置计时
      reset() {
        //重置
        clearInterval(this.time)
        this.hour = 0
        this.minute = 0
        this.ms = 0
        this.second = 0
        this.str = '00:00:00'
      },
      //定义计时函数
      timer() {
        //定义计时函数
        this.ms = this.ms + 50 //毫秒
        if (this.ms >= 1000) {
          this.ms = 0
          this.second = this.second + 1 //秒
        }
        if (this.second >= 60) {
          this.second = 0
          this.minute = this.minute + 1 //分钟
        }
        if (this.minute >= 60) {
          this.minute = 0
          this.hour = this.hour + 1 //小时
        }
        this.str =
          this.toDub(this.hour) +
          ':' +
          this.toDub(this.minute) +
          ':' +
          this.toDub(this.second) /*+""+this.toDubms(this.ms)+"毫秒"*/

        // document.getElementById('mytime').innerHTML=h+"时"+m+"分"+s+"秒"+ms+"毫秒";
      },
      //开始计时
      timeStart() {
        this.time = setInterval(this.timer, 50)
      },
      startRecorder() {
        recorder.start().then(
          () => {},
          (error) => {
            // 出错了
            console.log(`${error.name} : ${error.message}`)
          }
        )
      },
      // 继续录音
      resumeRecorder() {
        recorder.resume()
      },
      // 暂停录音
      pauseRecorder() {
        recorder.pause()
      },
      // 结束录音
      stopRecorder() {
        recorder.stop()
      },
      // 录音播放
      playRecorder() {
        recorder.play()
      },
      // 暂停录音播放
      pausePlayRecorder() {
        recorder.pausePlay()
      },
      // 恢复录音播放
      resumePlayRecorder() {
        recorder.resumePlay()
      },
      // 停止录音播放
      stopPlayRecorder() {
        recorder.stopPlay()
      },
      // 销毁录音
      destroyRecorder() {
        if (recorder != null)
          recorder.destroy().then(function () {
            recorder = null
          })
      },
      /**
       * 获取录音文件
       * */
      getRecorder() {
        let toltime = recorder.duration //录音总时长
        let fileSize = recorder.fileSize //录音总大小
        //录音结束，获取取录音数据
        let PCMBlob = recorder.getPCMBlob() //获取 PCM 数据
        let wav = recorder.getWAVBlob() //获取 WAV 数据
        let channel = recorder.getChannelData() //获取左声道和右声道音频数据
      },
      //下载pcm
      downPCM() {
        //这里传参进去的时文件名
        recorder.downloadPCM('新文件')
      },
      //下载wav
      downWAV() {
        //这里传参进去的时文件名
        recorder.downloadWAV('新文件')
      },
      /*** 获取麦克风权限* */
      getPermission() {
        Recorder.getPermission().then(
          () => {
            this.$Message.success('获取权限成功')
          },
          (error) => {
            console.log(`${error.name} : ${error.message}`)
          }
        )
      },
      /*** 文件格式转换 wav-map3* */
      getMp3Data() {
        const mp3Blob = this.convertToMp3(recorder.getWAV())
        recorder.download(mp3Blob, 'recorder', 'mp3')
      },
      convertToMp3(wavDataView) {
        // 获取wav头信息
        const wav = lamejs.WavHeader.readHeader(wavDataView) // 此处其实可以不用去读wav头信息，毕竟有对应的config配置
        const { channels, sampleRate } = wav
        const mp3enc = new lamejs.Mp3Encoder(channels, sampleRate, 128)
        // 获取左右通道数据
        const result = recorder.getChannelData()
        const buffer = []
        const leftData =
          result.left &&
          new Int16Array(result.left.buffer, 0, result.left.byteLength / 2)
        const rightData =
          result.right &&
          new Int16Array(result.right.buffer, 0, result.right.byteLength / 2)
        const remaining = leftData.length + (rightData ? rightData.length : 0)
        const maxSamples = 1152
        for (let i = 0; i < remaining; i += maxSamples) {
          const left = leftData.subarray(i, i + maxSamples)
          let right = null
          let mp3buf = null
          if (channels === 2) {
            right = rightData.subarray(i, i + maxSamples)
            mp3buf = mp3enc.encodeBuffer(left, right)
          } else {
            mp3buf = mp3enc.encodeBuffer(left)
          }
          if (mp3buf.length > 0) {
            buffer.push(mp3buf)
          }
        }
        const enc = mp3enc.flush()
        if (enc.length > 0) {
          buffer.push(enc)
        }
        return new Blob(buffer, { type: 'audio/mp3' })
      },
    },
  }
</script>

<style scoped></style>
